package top.roadvast.rabbitmq.consumer;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.springframework.boot.test.context.SpringBootTest;
import top.roadvast.rabbitmq.utils.RabbitmqUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 8:58
 * @Version 1.0
 * @Description rabbitmq六种工作模式之一：扇出模式
 * 将日志打印到控制台
 */
@SpringBootTest
public class FanoutConsumer01 {
    public static void main(String[] args) throws IOException {
        final Connection connection = RabbitmqUtil.getConnection();
        final Channel channel = connection.createChannel();
        //参数：交换机名称，交换机类型
        channel.exchangeDeclare("logs", "fanout");
        //非持久,独占,自动删除
        final String queueName = channel.queueDeclare().getQueue();
        //把该队列,绑定到 logs 交换机
        //对于 fanout 类型的交换机, routingKey会被忽略，不允许null值
        channel.queueBind(queueName, "logs", "");
        System.out.println("等待接收数据：");
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            final String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            System.out.println("接收到消息：" + msg);
        };
        CancelCallback cancelCallback = (consumerTag) -> {

        };
        channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
    }
}
